<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="租户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入租户名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contactName">
        <el-input
          v-model="queryParams.contactName"
          placeholder="请输入联系人"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactMobile">
        <el-input
          v-model="queryParams.contactMobile"
          placeholder="请输入联系电话"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="租户状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="租户状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_tenant_package_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="过期时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:tenant:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:tenant:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:tenant:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:tenant:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tenantList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="租户编号" prop="id" width="120" />
      <el-table-column label="租户名称" prop="name" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="联系人" prop="contactName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="联系电话" prop="contactMobile" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="绑定域名" prop="website" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="租户套餐" prop="packageName" width="100" />
      <el-table-column label="租户状态" align="status" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" prop="expireTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.expireTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="租户名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入租户名称" />
        </el-form-item>
        <el-form-item prop="contactName" label="联系人">
          <el-input v-model="form.contactName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item prop="contactMobile" label="联系人手机">
          <el-input v-model="form.contactMobile" placeholder="请输入联系人手机" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="website">
          <span slot="label">
            <el-tooltip content="标准域名地址，如：www.baidu.com" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            绑定域名
          </span>
          <el-input v-model="form.website" placeholder="请输入域名" />
        </el-form-item>
        <el-form-item label="租户状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_tenant_package_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="租户套餐" prop="packageId">
          <el-select
            v-model="form.packageId"
            placeholder="租户套餐"
            clearable
            style="width: 300px"
          >
            <el-option
              v-for="dict in packageList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            v-model="form.expireTime"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="租户管理员账号密码" :visible.sync="openAccount" width="400px" append-to-body
               :show-close="false"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <p
        style="
              color: #ff0817;
              font-size: 18px;
              line-height: 30px;
              text-indent: 2em;
            "
      >
        已为您在Nuyoah管理系统创建“{{
        account.tenant
        }}”租户信息及管理员用户，账号：{{ account.username }}， 密码：{{
        account.password
        }}，请妥善管理好账号密码，及时登录系统修改密码。关闭页面前，请下载账号信息保存。
      </p>
      <div slot="footer" style="text-align: center" class="dialog-footer">
        <el-button type="primary" @click="downloadText()">下载</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { page,create,update,deleteTenant,getTenant,changeTenantStatus } from "@/api/system/tenant";
import { getPackageByStatus } from "@/api/system/tenantPackage";
import fileSaver from "file-saver/dist/FileSaver";

export default {
  name: "tenant",
  dicts: ['sys_tenant_package_status','sys_user_sex'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      tenantList: [],
      //套餐
      packageList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        contactName: undefined,
        contactMobile: undefined,
        status: undefined
      },
      //租户初始化账号信息
      account:{},
      //是否显示账号信息弹框
      openAccount: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "租户名称不能为空", trigger: "blur" }
        ],
        contactName: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" }
        ],
        contactMobile: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "联系人性别不能为空", trigger: "blur" }
        ],
        website: [
          { required: true, message: "域名不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "租户状态不能为空", trigger: "blur" }
        ],
        packageId: [
          { required: true, message: "租户套餐不能为空", trigger: "blur" }
        ],
        expireTime: [
          { required: true, message: "过期时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      page(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.tenantList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"租户吗？').then(function() {
        const param = {id:row.id,status:row.status};
        return changeTenantStatus(param);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    //获取租户套餐
    getTenantPackageList() {
      getPackageByStatus().then(res=>{
        this.packageList=res.data;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
        this.form = {
          id: undefined,
          name: undefined,
          contactName: undefined,
          contactMobile: undefined,
          website: undefined,
          expireTime:undefined,
          packageId:undefined,
          status: "0",
        };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.getTenantPackageList();
      this.title = "添加租户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTenantPackageList();
      const id = row.id || this.ids
      getTenant(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改租户";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            update(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            create(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openAccount=true;
              console.log(response.data)
              this.account=response.data;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除租户编号为"' + ids + '"的数据项？').then(function() {
        return deleteTenant(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/tenant/export', {
        ...this.queryParams
      }, `租户_${new Date().getTime()}.xlsx`)
    },
    //新增租户时初始化一个租户管理员账号，账号信息下载
    downloadText(){
      const data = process.env.VUE_APP_TITLE+'的初始化租户管理员账号密码为：'
        +'\r\n账号：' +this.account.username
        +'\r\n密码：' +this.account.password
        +'\r\n请妥善保管账号密码并及时登录系统修改密码'
      var blob = new Blob([data], { type: 'text/plain;charset=utf-8' })
      fileSaver.saveAs(blob, this.account.tenant+'租户管理员信息.txt');
      this.openAccount=false;
      this.open = false;
      this.getList();
    }
  }
};
</script>
